package models

import (
	"bytes"
	"fmt"
	"github.com/astaxie/beego"
	"github.com/astaxie/beego/orm"
	"strings"
)

type AlgoInfoConfig struct {
	Id           int64  `orm:"column(id);auto" json:"id" form:"id"`
	No           int64  `orm:"column(no)" json:"no" form:"no"`
	AlgoName     string `orm:"column(algo_name)" json:"algo_name" form:"algo_name"`
	SkillId      string `orm:"column(skill_id)" json:"skill_id" form:"skill_id"`
	ModelId      string `orm:"column(model_id)" json:"model_id" form:"model_id"`
	ImageAddr    string `orm:"column(image_addr)" json:"image_addr" form:"image_addr"`
	AlgoPort     string `orm:"column(algo_port)" json:"algo_port" form:"algo_port"`
	HostDir      string `orm:"column(host_dir)" json:"host_dir" form:"host_dir"`
	Cmd          string `orm:"column(cmd)" json:"cmd" form:"cmd"`
	Args         string `orm:"column(args)" json:"args" form:"args"`
	Envs         string `orm:"column(envs)" json:"envs" form:"envs"`
	CreateTime   string `orm:"column(create_time)" json:"create_time" form:"create_time"` //创建s时间
	UpdateTime   string `orm:"column(update_time)" json:"update_time" form:"update_time"` //创建s时间
	NodeSelector string `orm:"column(node_selector)" json:"node_selector" form:"node_selector"`
	AlgoType     string `orm:"column(algo_type)" json:"algo_type" form:"algo_type"` // decode,algo
	AlgoStatus   string `orm:"column(algo_status)" json:"algo_status" form:"algo_status"`
	AlgoRes      string `orm:"column(algo_res)" json:"algo_res" form:"algo_res"`
	Cids         string `orm:"column(cids)" json:"cids" form:"cids"`
	Port         string `orm:"column(port)" json:"port" form:"port"`
}

func (dc *AlgoInfoConfig) TableName() string {
	return "algo_info_config"
}
func init() {
	orm.RegisterModel(new(AlgoInfoConfig))
}

func AddAlgoInfoConfig(c *AlgoInfoConfig) (id int64, err error) {
	o := orm.NewOrm()
	id, err = o.Insert(c)
	return
}
func GetAlgoInfoConfigByParams(model_id string) (data *AlgoInfoConfig, err error) {
	o := orm.NewOrm()
	err = o.Raw("SELECT * FROM algo_info_config where   model_id=? ", model_id).QueryRow(&data)
	return
}
func GetAlgoInfoConfigBySkillId(skill_id string) (data *AlgoInfoConfig, err error) {
	o := orm.NewOrm()
	err = o.Raw("SELECT * FROM algo_info_config where   skill_id = ?", skill_id).QueryRow(&data)
	return
}
func UpdateAlgoInfoConfig(c *AlgoInfoConfig, upfields []string) (err error) {
	o := orm.NewOrm()
	v := AlgoInfoConfig{Id: c.Id}
	if err := o.Read(&v); err == nil {
		if _, err := o.Update(c, upfields...); err == nil {
			return nil
		}
	}
	return
}
func GetAlgoInfoConfigById(id int64) (c *AlgoInfoConfig, err error) {
	o := orm.NewOrm()
	c = &AlgoInfoConfig{Id: id}
	if err := o.Read(c); err == nil {
		return c, nil
	} else {
		return nil, err
	}
}
func GetAlInfoConfigList(skill_id, algo_status, algo_type string) (alinfoList []*AlgoInfoConfig, err error) {
	o := orm.NewOrm()
	sb := new(bytes.Buffer)
	sb.WriteString(fmt.Sprintf("SELECT * FROM algo_info_config "))
	//if strings.TrimSpace(algo_type) != "" {
	sb.WriteString("where algo_type='" + algo_type + "'")
	//}
	if strings.TrimSpace(skill_id) != "" {
		sb.WriteString(" and skill_id like'%" + skill_id + "%'")
	}
	if strings.TrimSpace(algo_status) != "" {
		sb.WriteString(" and algo_status='" + strings.TrimSpace(algo_status) + "'")
	}
	sb.WriteString(" order by id desc")
	beego.Info(sb.String())
	_, err = o.Raw(sb.String()).QueryRows(&alinfoList)
	return
}

//get list
func GetAllAlInfoConfig(query, queryf map[string]string, fields, sortby, order []string, pageSize, offset int64) (cms []*AlgoInfoConfig, count int64, err error) {
	o := orm.NewOrm()
	qs := o.QueryTable(new(AlgoInfoConfig))
	for k, v := range query {
		qs = qs.Filter(k, v)
	}
	for k, v := range queryf {
		qs = qs.FilterRaw(k, v)
	}
	count, _ = qs.Count()
	var sortFields []string
	if len(sortby) == len(order) {
		for i, v := range sortby {
			orderby := ""
			if order[i] == "desc" {
				orderby = "-" + v
			} else if order[i] == "asc" {
				orderby = v
			}
			sortFields = append(sortFields, orderby)
		}
	}
	qs = qs.OrderBy(sortFields...)
	if _, err = qs.Limit(pageSize, offset).All(&cms, fields...); err != nil {
		return nil, 0, err
	}
	for k, v := range cms {
		v.No = offset + int64(k) + 1
	}
	return
}

type SkillIds struct {
	SkillId string `json:"skill_id"`
}
func GetDistinctSkillId(algo_type string) (skillIds []*SkillIds, err error) {
	o := orm.NewOrm()
	s := "select distinct skill_id from oil_algo where algo_type='" + algo_type + "' order by  skill_id  asc;"

	_, err = o.Raw(s).QueryRows(&skillIds)
	return
}
func DeleteAlgoInfoConfig(id int64) (err error) {
	o := orm.NewOrm()
	c := AlgoInfoConfig{Id: id}
	if err := o.Read(&c); err == nil {
		if _, err := o.Delete(&c); err == nil {
			return nil
		}
	}
	return
}
